%in_path = 'D:\Projects\AoT\testPrepData';
%ground_truth_path = 'D:\Projects\AoT\FromUMICH\car';

in_path = '../../prepUMICHData';
ground_truth_path = '../../FromUMICH/car';

out_path = in_path;
all_res= cell(0);
i_inst= 0;
targets = [];
outputs = [];
order = [];
poseHat = [];
pose=[];
file_list = dir([in_path '/*results.mat']);
n_file = length(file_list);
for i_file = 1 : n_file
    % read groudtruth
    load([in_path '/' file_list(i_file).name(1:end-12) '.view.mat']);
    % read result
    load([in_path '/' file_list(i_file).name] );
    n_inst = size(result,1);
    result = result(1:min(n_inst,1),:);
    INST_DETECTED=false;
    SUCCESS = false;
   
    name = file_list(i_file).name(1:end-12);
    gt_pose = str2num(name(end-6));

    for i_inst = 1:size(result,1);
        inst =  result(i_inst,:);
        [m_row,m_col]=ind2sub([300 400],inst(6)+1);
        view.m_row = m_row; view.m_col = m_col;
        view.m_pan = inst(7);
        view.m_tilt = inst(8);
        view.m_roll = inst(9);
        view.m_dist = inst(10);
        view.m_score = inst(1);
        view.f = 600;
        view.P = raiseViewPoint(view.m_pan,view.m_tilt,view.m_roll,view.m_dist);



	% figure out the post estimate
	panTable=[90,45,0,315,270,225,180,135];
	pan = view.m_pan;
	panDist = min( abs(pan-panTable),abs(pan+2*pi-panTable) );
	[val est_pose] = min(panDist);
	pose = [pose; gt_pose];
	poseHat =[poseHat; est_pose];	

    %% show the projected bounding box
    file_name_head = file_list(i_file).name(1:end-12);
    img = imread([in_path '/' file_name_head '.jpg']);
    view.bd=testProjection(view.P,img,1,1,m_row*2,m_col*2); 

    %% get estimated bounding box from image
    img = imread([in_path '/' file_name_head '_instance_' num2str(i_inst-1,'%02d') '.bmp']);
    index= find(img<35);
    [ind_row ind_col]=ind2sub(size(img),index);
    bd = zeros(4,1);
    bd(1)=min(ind_col);
    bd(2)=max(ind_col);
    bd(3)=min(ind_row);
    bd(4)=max(ind_row);
    view.bd = bd;
    
 %% read groundtruth
    int_bd = gt_bd;
    int_bd(1) = max(gt_bd(1),view.bd(1));
    int_bd(2) = min(gt_bd(2),view.bd(2));
    int_bd(3) = max(gt_bd(3),view.bd(3));
    int_bd(4) = min(gt_bd(4),view.bd(4));



if usejava('desktop')
    hold on;
    plot(view.bd([1 1 2 2 1]),view.bd([3 4 4 3 3]), 'b','linewidth',2);
    plot(gt_bd([1 1 2 2 1]),gt_bd([3 4 4 3 3]), 'g','linewidth',2);
    plot(int_bd([1 1 2 2 1]),int_bd([3 4 4 3 3]), 'r','linewidth',2); 
end
    area1 = (view.bd(2)-view.bd(1))*(view.bd(4)-view.bd(3));
    area2 = (gt_bd(2)-gt_bd(1))*(gt_bd(4)-gt_bd(3));
    area_int = (int_bd(2)-int_bd(1))*(int_bd(4)-int_bd(3));
    overlap = area_int/(area1+area2-area_int);
    %% show if detection is right or wrong
    if (overlap>0.5&&INST_DETECTED==false)
        INST_DETECTED = true;
        SUCCESS=true;
        view.gtlabel = 1;
        order = [order ; i_inst];
    else
        SUCCESS=false;
        view.gtlabel = -1;
    end
 
if usejava('desktop')
   if(SUCCESS)
        text(10,280,[ 'overlap: ' num2str(overlap)],'color','g'); 
    else
        text(10,280,['overlap: ' num2str(overlap)],'color','r');
    end
    text(150,280,['score:' num2str(view.m_score)],'fontsize',12,'color','r');
    saveas(gcf,[out_path '/' file_name_head 'inst_' num2str(i_inst) '.png'])
end


    %% put to the final strucgture
    i_inst = i_inst + 1;
    all_res{i_inst} =view;
    targets = [targets; view.gtlabel];
    outputs = [outputs; view.m_score];
    close
    end
end



%% report roc and pr curve
%prec_rec(outputs,targets,'plotROC',0,'plotPR',1,'plotBaseline',0,'style','r');


%%pose esimation
pose1 = pose(targets==1);
poseHat1 = poseHat(targets==1);
mat = confusionmat(pose1,poseHat1);
for i = 1:8
	mat(i,:) = mat(i,:)/sum(mat(i,:));
end
ap_pose = mean(diag(mat));
csvwrite('confmat.csv',mat);


figure;
%targets = targets(1:n_file);
%outputs = outputs(1:n_file);
n_pos = n_file;
[val ind]=sort(-outputs);
targets = targets(ind);
fp = cumsum(targets==-1);
tp = cumsum(targets==1);
rec = tp/n_pos;
prec = tp./(fp+tp);
ap = VOCap(rec,prec);
plot(rec,prec,'r','linewidth',2);
grid;
xlabel 'recall'
ylabel 'precision'
axis([0 1 0 1])
title( [ 'AP:' num2str(ap)]);


%system('python plotConf.py');
